<template>
  <view class="game-container">
    <!-- 游戏头部 -->
    <game-header 
      :current-level="gameStore.currentLevel"
      @save="handleSaveGame"
      @exit="handleExitGame"
      @back="handleBack"
    />
    
    <!-- 游戏信息面板 -->
    <view class="info-panel">
      <view class="info-item">
        <text class="info-label">目标颜色</text>
        <view class="color-display">
          <view class="color-indicator" :style="{ backgroundColor: gameStore.targetColor }"></view>
          <text class="color-name">{{ targetColorName }}</text>
        </view>
      </view>
      
      <view class="info-item">
        <text class="info-label">已用步数</text>
        <text class="info-value">{{ gameStore.stepsUsed }}/{{ gameStore.maxSteps }}</text>
      </view>
      
      <view class="info-item">
        <text class="info-label">完成度</text>
        <text class="info-value">{{ gameStore.progressPercentage }}%</text>
      </view>
      
      <view class="info-item">
        <text class="info-label">提示</text>
        <text class="info-value">{{ gameStore.hintsRemaining }}</text>
      </view>
    </view>
    
    <!-- 步骤进度 -->
    <view class="steps-progress">
      <view class="progress-label">步骤进度</view>
      <view class="progress-bars">
        <view 
          v-for="(step, index) in gameStore.maxSteps" 
          :key="index"
          class="progress-bar"
          :class="{
            'completed': index < gameStore.stepsUsed,
            'current': index === gameStore.stepsUsed,
            'future': index > gameStore.stepsUsed
          }"
        ></view>
      </view>
    </view>
    
    <!-- 游戏网格 -->
    <view class="game-grid-container">
      <game-grid 
        :grid="gameStore.grid"
        :selected-cell="gameStore.selectedCell"
        :cell-size="cellSize"
        @cell-click="handleCellClick"
      ></game-grid>
    </view>
    
    <!-- 颜色选择面板 -->
    <view class="color-palette-container">
      <text class="palette-label">选择颜色</text>
      <color-palette 
        :colors="usedColors"
        :selected-color="gameStore.currentColor"
        :is-animating="gameStore.isAnimating"
        @color-select="handleColorSelect"
      ></color-palette>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn" @click="handleRestart">
        <text class="btn-icon">↺</text> 重新开始
      </button>
      <button class="action-btn" @click="handleHint">
        <text class="btn-icon">💡</text> 提示
      </button>
    </view>
    
    <!-- 结果模态框 -->
    <view class="modal-mask" v-if="gameStore.gameCompleted">
      <view class="result-modal">
        <view class="result-icon" :class="resultIconClass">
          <text>{{ resultIcon }}</text>
        </view>
        <text class="result-title">{{ resultTitle }}</text>
        
        <view class="result-details">
          <text>完成步数: {{ gameStore.stepsUsed }} / 最优步数: {{ gameStore.optimalSteps }}</text>
          <text>连续通关: {{ gameStore.currentStreak }} 关</text>
        </view>
        
        <view class="result-score">
          <text class="score-label">获得积分</text>
          <text class="score-value">{{ resultScore }}</text>
        </view>
        
        <view class="result-buttons">
          <button 
            class="result-btn primary" 
            @click="handleNextLevel"
            v-if="gameStore.currentLevel < 15"
          >
            下一关
          </button>
          <button class="result-btn primary" @click="handlePlayAgain">再玩一次</button>
          <button class="result-btn secondary" @click="handleCloseResult">返回关卡</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { useGameStore } from '@/store/game'
import { useUserStore } from '@/store/user'
import GameGrid from '@/components/game-grid.vue'
import ColorPalette from '@/components/color-palette.vue'
import GameHeader from '@/components/game-header.vue'
import { useRouter } from 'vue-router'

const gameStore = useGameStore()
const userStore = useUserStore()
const router = useRouter()

// 计算属性
const targetColorName = computed(() => {
  const color = gameStore.COLORS.find(c => c.code === gameStore.targetColor)
  return color ? color.name : '未知'
})

const usedColors = computed(() => {
  const colors = new Set()
  const config = gameStore.DIFFICULTY_CONFIG[gameStore.currentDifficulty]
  
  for (let y = 0; y < config.gridSize; y++) {
    for (let x = 0; x < config.gridSize; x++) {
      if (gameStore.grid[y] && gameStore.grid[y][x]) {
        colors.add(gameStore.grid[y][x])
      }
    }
  }
  
  return Array.from(colors).map(color => ({
    code: color,
    name: gameStore.COLORS.find(c => c.code === color)?.name || '未知'
  }))
})

const cellSize = computed(() => {
  const config = gameStore.DIFFICULTY_CONFIG[gameStore.currentDifficulty]
  return Math.min(40, Math.floor(uni.getSystemInfoSync().windowWidth * 0.8 / config.gridSize))
})

// 结果相关状态
const resultTitle = ref('')
const resultIcon = ref('🏆')
const resultIconClass = ref('victory')
const resultScore = ref(0)

// 监听游戏完成状态
watch(() => gameStore.gameCompleted, (completed) => {
  if (completed) {
    const isVictory = gameStore.progressPercentage === 100
    resultTitle.value = isVictory ? '恭喜通关！' : '挑战失败'
    resultIcon.value = isVictory ? '🏆' : '😢'
    resultIconClass.value = isVictory ? 'victory' : 'defeat'
    
    if (isVictory) {
      resultScore.value = gameStore.calculateAndSaveScore()
      userStore.updateUserScore(gameStore.totalScore)
    }
  }
})

// 新增的事件处理方法
const handleSaveGame = () => {
  // 游戏头部组件已处理保存逻辑
  console.log('游戏已保存')
}

const handleExitGame = () => {
  // 游戏头部组件已处理退出逻辑
  console.log('游戏已退出')
}

const handleBack = () => {
  // 游戏头部组件已处理返回逻辑
  console.log('返回上一级')
}

// 原有的事件处理
const handleCellClick = (x, y) => {
  if (!gameStore.gameCompleted && !gameStore.isAnimating) {
    gameStore.selectedCell = { x, y }
    gameStore.currentColor = gameStore.grid[y][x]
  }
}

const handleColorSelect = (color) => {
  gameStore.fillColor(color)
}

const handleRestart = () => {
  if (!gameStore.isAnimating) {
    gameStore.initLevel()
  }
}

const handleHint = () => {
  const bestColor = gameStore.showHint()
  if (bestColor) {
    uni.showToast({
      title: '已提示最佳颜色',
      icon: 'none',
      duration: 2000
    })
  } else if (gameStore.hintsRemaining <= 0) {
    uni.showToast({
      title: '提示次数已用完',
      icon: 'none',
      duration: 2000
    })
  }
}

const handleNextLevel = () => {
  if (gameStore.currentLevel < 15) {
    gameStore.currentLevel++
    gameStore.initLevel()
  }
}

const handlePlayAgain = () => {
  gameStore.initLevel()
}

const handleCloseResult = () => {
  router.push('/pages/level-select/level-select')
}

// 页面生命周期
onShow(() => {
  // 恢复游戏状态
  gameStore.initGameState()
})

onHide(() => {
  // 自动保存
  gameStore.saveGameState()
})

// 初始化关卡
gameStore.initLevel()
</script>

<style scoped>
.game-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  padding: 0;
  display: flex;
  flex-direction: column;
}

.info-panel {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  background-color: rgba(30, 30, 50, 0.7);
  border-radius: 0;
  margin: 0;
  border-bottom: 1rpx solid rgba(108, 92, 231, 0.2);
}

.info-item {
  flex: 1 1 120rpx;
  margin: 8rpx;
  text-align: center;
}

.info-label {
  display: block;
  font-size: 24rpx;
  color: #888;
  margin-bottom: 8rpx;
}

.info-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
}

.color-display {
  display: flex;
  align-items: center;
  justify-content: center;
}

.color-indicator {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  margin-right: 8rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.3);
}

.color-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #fff;
}

.steps-progress {
  margin-bottom: 24rpx;
}

.progress-label {
  font-size: 28rpx;
  color: #888;
  margin-bottom: 8rpx;
}

.progress-bars {
  display: flex;
  gap: 8rpx;
  overflow-x: auto;
  padding-bottom: 8rpx;
}

.progress-bar {
  flex: 1;
  height: 16rpx;
  border-radius: 8rpx;
  min-width: 16rpx;
}

.progress-bar.completed {
  background-color: #6C5CE7;
}

.progress-bar.current {
  background-color: transparent;
  border: 2rpx solid #6C5CE7;
}

.progress-bar.future {
  background-color: #333;
}

.game-grid-container {
  display: flex;
  justify-content: center;
  margin-bottom: 24rpx;
}

.color-palette-container {
  background-color: rgba(30, 30, 50, 0.7);
  padding: 16rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
}

.palette-label {
  font-size: 28rpx;
  color: #fff;
  margin-bottom: 16rpx;
  display: block;
}

.action-buttons {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  flex: 1;
  background-color: #6C5CE7;
  color: #fff;
  padding: 16rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-icon {
  margin-right: 8rpx;
}

.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.result-modal {
  background-color: #1a1a2e;
  border-radius: 16rpx;
  padding: 32rpx;
  width: 80%;
  max-width: 500rpx;
  text-align: center;
}

.result-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin: 0 auto 16rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 64rpx;
}

.result-icon.victory {
  background: linear-gradient(to right, #FFD700, #FFA500);
}

.result-icon.defeat {
  background: linear-gradient(to right, #666, #333);
}

.result-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 24rpx;
}

.result-details {
  font-size: 28rpx;
  color: #ccc;
  margin-bottom: 24rpx;
  line-height: 1.5;
}

.result-score {
  background-color: rgba(255, 215, 0, 0.2);
  border: 1px solid rgba(255, 215, 0, 0.3);
  border-radius: 8rpx;
  padding: 16rpx;
  margin-bottom: 24rpx;
}

.score-label {
  display: block;
  font-size: 24rpx;
  color: #ccc;
  margin-bottom: 8rpx;
}

.score-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #FFD700;
}

.result-buttons {
  display: flex;
  gap: 16rpx;
}

.result-btn {
  flex: 1;
  padding: 16rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.result-btn.primary {
  background-color: #6C5CE7;
  color: #fff;
}

.result-btn.secondary {
  background-color: #333;
  color: #fff;
}
</style>